#include "Socket.hpp"
#include "Common.hpp"
#include "Protocol.hpp"
#include <iostream>
#include <string>
#include <memory>
#include <cstdio>

void Usage(string proc)
{
    cerr << "Usage: " << proc << " server_ip server_port" << endl;
}

void GetDataFromStdin(int *x, int *y, char *oper)
{
    cout << "Please Enter x: ";
    cin >> *x;
    cout << "Please Enter y: ";
    cin >> *y;
    cout << "Please Enter oper: ";
    cin >> *oper;
}

// ./tcpclient server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERRO);
    }
    string server_ip = argv[1];
    //uint16_t server_port = stoi(argv[2]);
    uint16_t server_port = 8081;
    shared_ptr<Socket> client = make_shared<TcpSocket>();
    client->BuildTcpClientSocketMethod();

    if (client->Connect(server_ip, server_port) != 0)
    {
        
        cerr << "connect error" << endl;
        exit(CONNECT_ERRO);
    }
    unique_ptr<Protocol> protocol = make_unique<Protocol>();
    string resp_buffer;
    
    while (true)
    {
     
        int x, y;
        char oper;
        GetDataFromStdin(&x, &y, &oper);

      
        string req_str = protocol->BuildRequestString(x, y, oper);

       
       
        client->Send(req_str);

      
        Respond resp;
        bool res = protocol->GetRespond(client, resp_buffer, &resp);
        if(res == false)
            break;

        
        resp.ShowResult();
    }
    client->Close();
    return 0;
}
